<template>
  <el-container>
    <el-header style="text-align: right; font-size: 12px">
      <!-- ============头部查询部分============开始 -->
      <div id="form">
        <el-form :inline="true" :model="ruleForm" ref="ruleForm">
          <el-form-item label="用户名">
            <el-input
              class="input"
              v-model="ruleForm.username"
              type="text"
              size="mini"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input
              class="input"
              v-model="ruleForm.name"
              type="text"
              size="mini"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select class="input select" v-model="ruleForm.status" size="mini" placeholder="全部">
              <el-option value="有效"></el-option>
              <el-option value="无效"></el-option>
            </el-select>
          </el-form-item>
          <!-- <span>组件值：{{ ruleForm.buildtime}}</span> -->
          <el-form-item label="创建时间">
            <div class="block input">
              <el-date-picker
                id="buildtime"
                size="mini"
                v-model="ruleForm.buildtime"
                type="daterange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </div>
          </el-form-item>
          <el-form-item class="allbtn">
            <!-- <a><i class="el-icon-search"></i></a> -->
            <el-button
              class="btn"
              size="mini"
              type="primary"
              icon="el-icon-search"
              @click="selectForm('ruleForm')"
            >查询</el-button>
            <el-button
              class="btn"
              size="mini"
              type="primary"
              icon="el-icon-circle-plus-outline"
              @click="insertList=true"
            >新增</el-button>
            <el-button
              class="btn"
              size="mini"
              type="primary"
              icon="el-icon-remove-outline"
              @click="deleteList()"
            >删除</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- ============头部查询部分============结束 -->
    </el-header>

    <!-- 表单弹框=================新增表单------开始 -->
    <el-dialog
      title="新增用户列表"
      :visible.sync="insertList"
      width="35%"
      top="2vh"
      :close-on-click-modal="false"
    >
      <el-form ref="tableData" :model="inputRule" :rules="inputRules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="inputRule.username"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="inputRule.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="inputRule.sex" size="small " placeholder="全部">
            <el-option value="男"></el-option>
            <el-option value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="inputRule.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="mail">
          <el-input v-model="inputRule.mail"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="inputRule.status" size="small " placeholder="全部">
            <el-option value="有效"></el-option>
            <el-option value="无效"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="insertList = false">取 消</el-button>
        <el-button type="primary" @click="addForm('tableData')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 表单弹框=================新增表单------结束 -->

    <!-- 表单弹框=================修改表单------开始 -->
    <el-dialog
      title="修改用户"
      :visible.sync="updateFlag"
      width="35%"
      top="2vh"
      :close-on-click-modal="false"
    >
      <el-form ref="dialogForm" :model="form"  label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="dialogForm.username"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="dialogForm.name"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="dialogForm.sex" size="small " placeholder="全部">
            <el-option value="男"></el-option>
            <el-option value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="dialogForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="dialogForm.mail"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="dialogForm.status" size="small " placeholder="全部">
            <el-option value="有效"></el-option>
            <el-option value="无效"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateFlag = false">取 消</el-button>
        <el-button type="primary" @click="updateUserManagerBtn('tableData')">修 改</el-button>
      </span>
    </el-dialog>
    <!-- 表单弹框=================修改表单------结束 -->

    <!-- =======================列表展示（开始）======================== -->
    <el-main>
      <!-- <router-view></router-view> -->
      <el-table
        id="table"
        ref="multipleTable"
        :data="tableData.slice((currentPage-1)*size,currentPage*size)"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" :index="indexMethod" label="序号" width="120"></el-table-column>
        <!-- <el-table-column prop="userManagerId" v-show="false" label="姓名" width="120"></el-table-column> -->
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="name" label="姓名" width="120"></el-table-column>
        <el-table-column prop="sex" :formatter="formatRole" label="性别" width="120"></el-table-column>
        <el-table-column prop="phone" label="联系电话" width="120"></el-table-column>
        <el-table-column prop="mail" label="邮箱" width="120"></el-table-column>
        <el-table-column prop="buildtime" label=" 创建时间" width="120"></el-table-column>
        <el-table-column prop="modifytime" label="最后修改时间" width="120"></el-table-column>
        <el-table-column prop="status" :formatter="formatStatus" label="状态" width="100"></el-table-column>
        <el-table-column label="操作" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="primary "
              prop="userManagerId"
              class="updatebtn"
              size="mini"
              @click="updateUserManager(scope.row)"
            >修改</el-button>
            <el-button type="danger " size="mini" @click="deleteForm(scope.row.userManagerId)">删除</el-button>
            <el-button type="warning " size="mini" @click="updateStatus(scope.row.userManagerId)">无效</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <!-- =======================列表展示（结束）======================== -->

    <!-- 尾部分页功能==================================开始 -->
    <el-footer>
      <div id="page">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[4, 8, 12, 16]"
          :page-size="4"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.length"
        ></el-pagination>
      </div>
    </el-footer>
    <!-- 尾部分页功能==================================结束 -->
  </el-container>
</template>

<script>
import { Message } from "element-ui";
export default {
  name: "UserList",
  data() {
    return {
      inputRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" }
        ],
        name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur"
          },
          {
            required: true,
            pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
            message: "姓名不支持特殊字符",
            trigger: "blur"
          }
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          {
            required: true,
            pattern: /^[1][3,4,5,7,8][0-9]{9}$/,
            message: "请输入正确的电话号码",
            trigger: "blur",
            // size:11
          }
        ],
        mail: [
          { required: true, message: "请输入邮箱地址" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        status: [{ required: true, message: "请选择状态", trigger: "blur" }]
      },
      val: "",
      form: {
        username: "",
        password: ""
      },
      // forms: {},
      ruleForm: {
        username: "",
        name: "",
        status: "",
        buildtime: ""
      },
      insertList: false,
      updateFlag: false,
      currentPage: 1,
      size: 4,
      uname: "",
      tableData: [
        {
          userManagerId: 0,
          username: "111",
          name: "zhangsan",
          sex: 1,
          phone: 18202714093,
          mail: "1464408796@qq.com",
          buildtime: "2020-1-7 12:12:14",
          modifytime: "2020-1-7 9:11:14",
          status: 0
        }
      ],
      multipleSelection: [],
      dialogForm: {
        userManagerId: 0,
        username: "",
        name: "",
        sex: 0,
        phone: 0,
        mail: "",
        status: 0
      },
      inputRule: {
        username: "",
        name: "",
        sex: "",
        phone: "",
        mail: "",
        status: ""
      }
      // value: "",
    };
  },
  methods: {
    // ------------------------表格后面的删除功能-------------------------------
    deleteForm(index) {
      console.log(index);
      var that = this;
      that.$http
        .get("/deleteById", {
          params: { id: index }
        })
        .then(function(response) {
          var data = response.data;
          // console.log(data);
          // that.tableData = data;
          if (data == 1) {
            Message({ message: "删除成功", type: "success" });
            // this.userManagerList();
            // window.location.reload();
            // this.reload();
            that.userManagerList();
          } else {
            Message({ message: "删除失败", type: "error" });
          }
        });
    },

    // --------------------------------编辑修改用户信息-------------------------------------

    updateUserManager(row) {
      this.updateFlag = true;
      this.dialogForm.userManagerId = row.userManagerId;
      this.dialogForm.username = row.username;
      this.dialogForm.name = row.name;
      this.dialogForm.sex = row.sex == 1 ? "男" : "女";
      this.dialogForm.mail = row.mail;
      this.dialogForm.phone = row.phone;
      this.dialogForm.status = row.status == 1 ? "有效" : "无效";
      // this.tableData=row;
    },

    updateUserManagerBtn(formName) {
      const param = new URLSearchParams();
      param.append("userManagerId", this.dialogForm.userManagerId);
      param.append("username", this.dialogForm.username);
      param.append("name", this.dialogForm.name);
      param.append("sex", this.dialogForm.sex == "男" ? 1 : 0);
      param.append("phone", this.dialogForm.phone);
      param.append("mail", this.dialogForm.mail);
      param.append("status", this.dialogForm.status == "有效" ? 1 : 0);
      // console.log(param.get("userManagerId"));
      var that = this;
      that
        .$http({
          method: "post",
          url: "/updateUserManager",
          data: param
        })
        .then(res => {
          if (res.data == 1) {
            console.log("-------" + this.tableData.username);
            Message({ message: "修改成功", type: "success" });
            // window.location.reload();
            this.userManagerList();
            console.log("登录成功");
          } else {
            Message({ message: "修改失败", type: "error" });
          }
        });
      this.updateFlag = false;
      // this.userManagerList();
    },
    // --------------------------------修改状态--------------------------------------

    updateStatus(index) {
      console.log(index);
      var that = this;
      that.$http
        .get("/updateStatusById", {
          params: { id: index }
        })
        .then(function(response) {
          var data = response.data;
          // console.log(data);
          // that.tableData = data;
          if (data == 1) {
            Message({ message: "修改成功", type: "success" });
            // this.userManagerList();
            // window.location.reload();
            // this.reload();
            that.userManagerList();
          } else {
            Message({ message: "修改失败", type: "error" });
          }
        });
    },
    // --------------------------------查询功能--------------------------------------
    selectForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const param = new URLSearchParams();
          param.append("username", this.ruleForm.username);
          param.append("name", this.ruleForm.name);
          let status;
          if (this.ruleForm.status == "有效") {
            status = 1;
          } else if (this.ruleForm.status == "无效") {
            status = 0;
          } else {
            status = -1;
          }
          param.append("status", status);
          const myDate =
            this.ruleForm.buildtime[0] == undefined ||
            undefined == this.ruleForm.buildtime[1]
              ? 0
              : this.ruleForm.buildtime[0] + "," + this.ruleForm.buildtime[1];
          param.append("builtime", myDate);
          // alert(typeof(myDate))
          console.log(myDate);
          var that = this;
          that
            .$http({
              method: "post",
              url: "/selectByForm",
              data: param
            })
            .then(res => {
              console.log(res.data);
              that.tableData = res.data;
            });
          // alert("submit");
        }
      });
    },
    // --------------------------------查询功能（结束）--------------------------------------

    // --------------------------------列表展示功能--------------------------------------
    userManagerList() {
      const that = this;
      this.$http
        .get("/managerlist")
        .then(function(response) {
          var data = response.data;
          // console.log(data);
          that.tableData = data;
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(this.multipleSelection);
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.size = val;
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
    },
    //判断性别    1 代表男性  0 代表女性
    formatRole(row, column) {
      // console.log(row)
      // console.log(column)
      // console.log(row.sex + "页面性别展示");
      return row.sex == 1 ? "男" : "女";
    },
    //判断状态    1 代表有效  0代表无效
    formatStatus(row, column) {
      // console.log(row.status + "页面状态展示");
      return row.status == 1 ? "有效" : "无效";
    },
    //设置序列
    indexMethod(index) {
      return (this.currentPage - 1) * this.size + index + 1;
    },

    // --------------------------------添加列表功能--------------------------------------
    addForm(formName) {
      console.log(formName);
      this.$refs[formName].validate(valid => {
        console.log(valid);
        if (valid) {
          const param = new URLSearchParams();
          param.append("username", this.inputRule.username);
          param.append("name", this.inputRule.name);
          param.append("sex", this.inputRule.sex == "男" ? 1 : 0);
          param.append("phone", this.inputRule.phone);
          param.append("mail", this.inputRule.mail);
          param.append("status", this.inputRule.status == "有效" ? 1 : 0);
          console.log(param.sex);
          var that = this;
          that
            .$http({
              method: "post",
              url: "/addUserManagerList",
              data: param
            })
            .then(res => {
              if (res.data == 1) {
                console.log("-------" + this.inputRule.username);
                Message({ message: "添加成功", type: "success" });
                // window.location.reload();multipleSelection
                // that.inputRule=null;
                this.userManagerList();
                console.log("登录成功");
              } else {
                Message({ message: "添加失败", type: "error" });
              }
              console.log(res);
            });
        } else {
          Message({ message: "添加失败", type: "error" });
        }
      });
      this.insertList = false;
    },
    //删除
    deleteList() {
      console.log(this.multipleSelection);
      var selectUsers = "";
      for (let i = 0; i < this.multipleSelection.length; i++) {
        selectUsers += this.multipleSelection[i].userManagerId + ",";
      }
      // alert(typeof(selectUsers));
      const that = this;
      that.$http
        .get("/removeManager", {
          params: { ids: selectUsers }
        })
        .then(function(response) {
          var data = response.data;
          if (data == 1) {
            Message({ message: "删除成功", type: "success" });
            // this.userManagerList();
            // window.location.reload();
            // this.reload();
            that.multipleSelection = [];
            that.$refs.multipleTable.clearSelection();
            that.userManagerList();
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    }
  },
  mounted: function() {
    // 页面初始化完成执行方法
    this.userManagerList();
  }
};
</script>


<style scoped>
.el-header {
  background-color: #b3c0d1;
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: #333;
}
#uname {
  margin-right: 20px;
}
#form {
  float: left;
}
.input {
  margin-top: 10px;
  width: 91px;
}
.select {
  width: 75px;
}
.el-table--scrollable-x .el-table__body-wrapper {
  overflow-x: hidden;
}
.el-table__body-wrapper .is-scrolling-middle {
  overflow-x: hidden;
}
#page {
  margin-left: 270px;
}
#buildtime {
  width: 123px;
}
.btn {
  margin-top: 16px;
  width: 75px;
}
.allbtn {
  margin-left: 220px;
}
.el-date-editor--daterange.el-input,
.el-date-editor--daterange.el-input__inner,
.el-date-editor--timerange.el-input,
.el-date-editor--timerange.el-input__inner {
  width: 262px;
}
/* #table{
  height: 600px;
} */
.updatebtn {
  margin-left: 10px;
}
</style>